package com.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.mall.entity.GoodsVisit;
import com.mall.enums.CodeNumEntity;
import com.mall.exception.ServiceException;
import com.mall.mapper.GoodsVisitMapper;
import com.mall.service.IGoodsVisitService;
import com.mall.util.DateUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 商品访问历史表 服务实现类
 * </p>
 * @author ShouPeng
 * @since 2023-04-19
 */
@Service
public class GoodsVisitServiceImpl implements IGoodsVisitService {
    final
    GoodsVisitMapper visitMapper;

    public GoodsVisitServiceImpl(GoodsVisitMapper visitMapper) {
        this.visitMapper = visitMapper;
    }

    /**
     * 添加商品访问历史
     * @param visit
     * @return
     */
    @Override
    public Boolean addVisitRecord(GoodsVisit visit) {
        //表示之前已经访问过该商品了，更新
        GoodsVisit record = visitMapper.selectOne(new QueryWrapper<GoodsVisit>().eq("goods_id", visit.getGoodsId()));
        if (ObjectUtils.isNotEmpty(record)) {
           visitMapper.deleteById(record.getVisitId());
        }
        visit.setVisitDate(DateUtils.currentDate());
        return visitMapper.insert(visit) > 0;
    }

    /**
     * 查询商品访问历史
     * @param userId
     * @return
     */
    @Override
    public List<GoodsVisit> queryGoodsVisitRecord(String userId) {
        return visitMapper.queryGoodsVisitRecord(userId);
    }

    @Override
    public int removeVisitHistory(String visitId) {
        int i = visitMapper.deleteByVisitId(visitId);
        if(i == 0)
            throw new ServiceException(CodeNumEntity.DATABASE_ERROR.getCode(), CodeNumEntity.DATABASE_ERROR.getMessage());
        return 1;
    }

    @Override
    public int clearGoodsHistory(String userId) {
        return visitMapper.clearGoodsHistory(userId);
    }
}
